import { ethers } from 'ethers';
import { Transaction, ChainType } from '@/types';
import { createModuleLogger } from '@/utils/logger';
import { PriceService } from '@/services/price/PriceService';
import { AddressLabelService } from '@/services/address/AddressLabelService';
import { ConfigService } from '@/services/config/ConfigService';
import config from '@/config';
import { ChainMonitorConfig } from '@/services/config/ChainMonitorConfigService';

const logger = createModuleLogger('ethereum-monitor');

export class EthereumMonitor {
  private provider: ethers.JsonRpcProvider;
  private wsProvider?: ethers.WebSocketProvider;
  private isRunning = false;
  private lastProcessedBlock = 0;
  private lastSuccessfulBlock = 0; // 记录最后成功处理的区块
  private onTransactionCallback?: (transaction: Transaction) => void;
  private requestQueue: Array<() => Promise<any>> = [];
  private isProcessingQueue = false;
  private requestDelay = 100; // 100ms between requests
  private priceService: PriceService;
  private addressLabelService?: AddressLabelService;
  private consecutiveErrors = 0; // 连续错误计数
  private maxConsecutiveErrors = 5; // 最大连续错误数
  private backfillInProgress = false; // 回溯进行中标志
  private configService: ConfigService | null = null;
  private chainConfig: ChainMonitorConfig | null = null;

  constructor() {
    // 使用第一个可用的备用RPC端点
    const rpcUrl = config.chains.ethereum.fallbackRpcUrls?.[0] || config.chains.ethereum.rpcUrl;
    this.provider = new ethers.JsonRpcProvider(rpcUrl);
    this.priceService = PriceService.getInstance();
    
    // 如果有WebSocket URL，创建WebSocket连接用于实时监控
    if (config.chains.ethereum.wssUrl) {
      this.wsProvider = new ethers.WebSocketProvider(config.chains.ethereum.wssUrl);
    }
  }

  // 请求队列处理，避免速率限制
  private async queueRequest<T>(requestFn: () => Promise<T>): Promise<T | null> {
    return new Promise((resolve) => {
      this.requestQueue.push(async () => {
        try {
          const result = await requestFn();
          resolve(result);
        } catch (error) {
          logger.debug('请求失败，跳过:', error instanceof Error ? error.message : error);
          resolve(null);
        }
      });

      this.processQueue();
    });
  }

  // 处理请求队列
  private async processQueue(): Promise<void> {
    if (this.isProcessingQueue || this.requestQueue.length === 0) {
      return;
    }

    this.isProcessingQueue = true;

    while (this.requestQueue.length > 0 && this.isRunning) {
      const request = this.requestQueue.shift();
      if (request) {
        await request();
        // 添加延迟避免速率限制
        await new Promise(resolve => setTimeout(resolve, this.requestDelay));
      }
    }

    this.isProcessingQueue = false;
  }

  // 设置交易回调函数
  public setTransactionCallback(callback: (transaction: Transaction) => void): void {
    this.onTransactionCallback = callback;
  }

  // 设置地址标记服务
  public setAddressLabelService(service: AddressLabelService): void {
    this.addressLabelService = service;
  }

  // 设置配置服务
  public setConfigService(configService: ConfigService): void {
    this.configService = configService;
  }

  public async setChainConfig(chainConfig: ChainMonitorConfig): Promise<void> {
    this.chainConfig = chainConfig;
    logger.info(`🔧 EthereumMonitor 配置已更新: min=$${chainConfig.minValueUsd}, rpc=${chainConfig.rpcUrl}`);
    
    // 如果配置了新的RPC URL，更新provider
    if (chainConfig.rpcUrl !== config.chains.ethereum.rpcUrl) {
      this.provider = new ethers.JsonRpcProvider(chainConfig.rpcUrl);
      logger.info(`🔄 EthereumMonitor RPC已更新: ${chainConfig.rpcUrl}`);
    }

    // 如果有WebSocket配置，更新WebSocket provider
    if (chainConfig.wssUrl && chainConfig.wssUrl !== config.chains.ethereum.wssUrl) {
      if (this.wsProvider) {
        try {
          await this.wsProvider.destroy();
        } catch (error) {
          logger.warn(`⚠️ WebSocket销毁警告: ${error}`);
        }
      }
      
      try {
      this.wsProvider = new ethers.WebSocketProvider(chainConfig.wssUrl);
      logger.info(`🔄 EthereumMonitor WebSocket已更新: ${chainConfig.wssUrl}`);
      } catch (error) {
        logger.error(`❌ WebSocket创建失败: ${error}`);
        this.wsProvider = undefined;
      }
    }

    // 更新请求延迟
    this.requestDelay = chainConfig.requestDelay || 100;
  }

  // 获取最小交易金额阈值
  private getMinTransactionValue(): number {
    if (this.chainConfig) {
      return this.chainConfig.minValueUsd;
    }

    if (this.configService) {
      const monitoringConfig = this.configService.getMonitoringConfig();
      return monitoringConfig.minTransactionValue;
    }
    return config.monitoring.defaultMinValue; // 回退到静态配置
  }

  // 开始监控
  public async start(): Promise<void> {
    if (this.isRunning) {
      logger.warn('⚠️ 以太坊监控已在运行中，跳过启动');
      return;
    }

    try {
      logger.info('🚀 正在初始化以太坊监控器...');
      // 显示实际使用的RPC端点（考虑数据库配置）
      const actualRpcUrl = this.chainConfig?.rpcUrl || config.chains.ethereum.rpcUrl;
      logger.info(`🔗 以太坊RPC端点: ${actualRpcUrl}`);
      logger.info(`📊 监控阈值: $${this.getMinTransactionValue().toLocaleString()}`);
      
      this.isRunning = true;
      
      // 测试RPC连接
      logger.info('🔍 测试以太坊RPC连接...');
      const networkInfo = await this.provider.getNetwork();
      logger.info(`✅ 以太坊网络连接成功: Chain ID ${networkInfo.chainId}, Name: ${networkInfo.name}`);
      
      // 获取当前最新区块号
      this.lastProcessedBlock = await this.provider.getBlockNumber();
      logger.info(`📊 以太坊监控器已连接，当前区块: ${this.lastProcessedBlock}`);

      // 初始化价格服务
      logger.info('💰 初始化价格服务...');
      await this.priceService.initialize();
      logger.info('✅ 价格服务已就绪，开始监控大额交易');

      // 如果有WebSocket连接，使用实时监控
      if (this.wsProvider) {
        logger.info('🔗 检测到WebSocket配置，启动实时监控模式...');
        await this.startRealtimeMonitoring();
        // 启用代币转账监控
        await this.monitorTokenTransfers();
        logger.info('🔗 以太坊实时监控模式已启动 (WebSocket + 代币转账监控)');
      } else {
        // 否则使用轮询模式
        logger.info('📡 使用轮询监控模式...');
        this.startPollingMonitoring(); // 非阻塞启动
        logger.info('📡 以太坊轮询监控模式已启动');
      }
    } catch (error) {
      logger.error('💥 启动以太坊监控失败:', error);
      this.isRunning = false;
      throw error;
    }
  }

  // 停止监控
  public async stop(): Promise<void> {
    logger.info('⏹️ 正在停止以太坊监控器...');
    
    if (!this.isRunning) {
      logger.warn('⚠️ 以太坊监控器已经停止，跳过操作');
      return;
    }
    
    this.isRunning = false;
    logger.info('🛑 已设置 isRunning = false，等待轮询循环结束...');
    
    if (this.wsProvider) {
      await this.wsProvider.destroy();
      logger.info('🔌 以太坊WebSocket连接已断开');
    }
    
    // 等待一个轮询周期，确保循环结束
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    logger.info('✅ 以太坊监控器已完全停止');
  }

  // 实时监控模式（WebSocket）
  private async startRealtimeMonitoring(): Promise<void> {
    if (!this.wsProvider) return;

    this.wsProvider.on('block', async (blockNumber: number) => {
      if (!this.isRunning) return;
      
      try {
        await this.processBlock(blockNumber);
      } catch (error) {
        logger.error(`处理区块 ${blockNumber} 失败:`, error instanceof Error ? error.message : String(error));
      }
    });

    logger.info('已启动以太坊实时监控 (WebSocket)');
  }

  // 区块回溯补偿机制
  private async backfillMissedBlocks(): Promise<void> {
    if (this.backfillInProgress || !this.isRunning) return;

    try {
      this.backfillInProgress = true;
      const currentBlock = await this.queueRequest(() => this.provider.getBlockNumber());
      
      if (!currentBlock || currentBlock <= this.lastSuccessfulBlock) {
        this.backfillInProgress = false;
        return;
      }

      const missedBlocks = currentBlock - this.lastSuccessfulBlock;
      
      if (missedBlocks > 1 && missedBlocks <= 50) { // 最多回溯50个区块
        logger.warn(`🔄 检测到 ${missedBlocks} 个漏掉的区块，开始回溯补偿...`);
        
        // 从最后成功的区块+1开始回溯
        for (let blockNum = this.lastSuccessfulBlock + 1; blockNum < currentBlock; blockNum++) {
          if (!this.isRunning) break;
          
          try {
            await this.processBlock(blockNum);
            this.lastSuccessfulBlock = blockNum;
            
            // 回溯时使用更长的延迟，避免再次触发速率限制
            await new Promise(resolve => setTimeout(resolve, 200));
            
          } catch (error) {
            logger.debug(`回溯区块 ${blockNum} 失败，跳过`);
            // 即使单个区块失败，也继续回溯其他区块
          }
        }
        
        logger.info(`✅ 区块回溯完成，已补偿到区块 ${this.lastSuccessfulBlock}`);
      } else if (missedBlocks > 50) {
        logger.warn(`⚠️ 漏掉区块过多 (${missedBlocks})，跳过回溯，从当前区块继续`);
        this.lastSuccessfulBlock = currentBlock - 1;
      }

    } catch (error) {
      logger.error('区块回溯失败:', error);
    } finally {
      this.backfillInProgress = false;
    }
  }

  // 轮询监控
  private async startPollingMonitoring(): Promise<void> {
    logger.info('🔄 以太坊轮询监控模式已启动');
    logger.info(`⏰ 轮询间隔: ${config.monitoring.blockCheckInterval}ms`);
    logger.info(`📊 监控阈值: $${this.getMinTransactionValue().toLocaleString()}`);
    
    while (this.isRunning) {
      try {
        const currentBlock = await this.queueRequest(() => this.provider.getBlockNumber());
        logger.debug(`📊 当前区块: ${currentBlock}, 已处理区块: ${this.lastProcessedBlock}`);
        
        if (currentBlock && currentBlock > this.lastProcessedBlock) {
          const blocksToProcess = currentBlock - this.lastProcessedBlock;
          logger.info(`🔄 需要处理 ${blocksToProcess} 个新区块 (${this.lastProcessedBlock + 1} 到 ${currentBlock})`);
          
          // 如果之前有连续错误，先尝试回溯补偿
          if (this.consecutiveErrors > 0) {
            await this.backfillMissedBlocks();
            this.consecutiveErrors = 0; // 重置错误计数
          }

          // 处理新区块
          for (let blockNum = this.lastProcessedBlock + 1; blockNum <= currentBlock; blockNum++) {
            if (!this.isRunning) break;
            
            try {
              logger.info(`🔍 开始处理区块: ${blockNum}`);
              await this.processBlock(blockNum);
              this.lastProcessedBlock = blockNum;
              this.lastSuccessfulBlock = blockNum; // 更新成功处理的区块
              logger.debug(`✅ 完成处理区块: ${blockNum}`);
              
            } catch (blockError) {
              logger.error(`处理区块 ${blockNum} 失败:`, blockError);
              // 单个区块失败不影响整体监控
              this.lastProcessedBlock = blockNum; // 仍然标记为已处理，避免重复
            }
          }
        } else {
          logger.debug('⏳ 没有新区块，等待下次检查...');
        }

        // 重置连续错误计数
        this.consecutiveErrors = 0;
        
      } catch (error) {
        this.consecutiveErrors++;
        
        if (this.consecutiveErrors <= this.maxConsecutiveErrors) {
          logger.warn(`轮询监控出错 (${this.consecutiveErrors}/${this.maxConsecutiveErrors}):`, error);
          
          // 指数退避策略
          const backoffDelay = Math.min(1000 * Math.pow(2, this.consecutiveErrors - 1), 30000);
          logger.info(`等待 ${backoffDelay/1000}秒 后重试...`);
          await new Promise(resolve => setTimeout(resolve, backoffDelay));
          
        } else {
          logger.error(`连续错误过多，暂停监控 30秒:`, error);
          await new Promise(resolve => setTimeout(resolve, 30000));
          this.consecutiveErrors = 0; // 重置计数
        }
      }

      // 正常轮询间隔
      if (this.isRunning && this.consecutiveErrors === 0) {
        await new Promise(resolve => setTimeout(resolve, config.monitoring.blockCheckInterval));
      }
    }
    
    logger.info('🏁 以太坊轮询监控循环已退出');
  }

  // 处理区块
  private async processBlock(blockNumber: number): Promise<void> {
    try {
      const block = await this.queueRequest(() => this.provider.getBlock(blockNumber, true));
      if (!block || !block.transactions) return;

      // 添加处理进度日志（每10个区块记录一次）
      if (blockNumber % 10 === 0) {
        logger.info(`📊 ETH监控进度: 区块 ${blockNumber}, 交易数: ${block.transactions.length}`);
      }

      // 限制每个区块处理的交易数量，避免过载
      const maxTransactions = config.monitoring.maxTransactionsPerBlock;
      const transactionsToProcess = block.transactions.slice(0, maxTransactions);
      
      let processedCount = 0;
      let largeTransactionCount = 0;

      for (const txHash of transactionsToProcess) {
        if (!this.isRunning) break;
        
        try {
          const tx = await this.queueRequest(() => this.provider.getTransaction(txHash));
          if (tx) {
            processedCount++;
            
            // 处理原生ETH交易
            await this.processTransaction(tx, block);
            
            // 检查是否有代币转账
            await this.checkTokenTransferInTransaction(tx, block);
          }
        } catch (error) {
          logger.debug(`处理交易失败 ${txHash}:`, error);
        }
      }

      // 每处理完一个区块，记录统计信息
      if (processedCount > 0) {
        logger.info(`📊 ETH区块 ${blockNumber}: 处理 ${processedCount}/${block.transactions.length} 笔交易`);
      }

    } catch (error) {
      logger.error(`处理区块 ${blockNumber} 失败:`, error instanceof Error ? error.message : String(error));
    }
  }

  // 检查交易中的代币转账
  private async checkTokenTransferInTransaction(tx: ethers.TransactionResponse, block: ethers.Block): Promise<void> {
    try {
      // 获取交易收据以查看事件日志
      const receipt = await this.queueRequest(() => this.provider.getTransactionReceipt(tx.hash));
      if (!receipt || !receipt.logs) return;

      // 查找Transfer事件
      const transferTopic = ethers.id('Transfer(address,address,uint256)');
      
      for (const log of receipt.logs) {
        if (log.topics[0] === transferTopic && log.topics.length >= 3) {
          await this.processTokenTransferFromLog(log);
        }
      }
    } catch (error) {
      logger.debug(`检查交易 ${tx.hash} 的代币转账失败:`, error);
    }
  }

  // 从日志处理代币转账
  private async processTokenTransferFromLog(log: any): Promise<void> {
    try {
      // 验证日志基本结构
      if (!log || !log.topics || log.topics.length < 3 || !log.data) {
        return; // 静默跳过无效日志
      }

      // 检查是否是Transfer事件 (topic[0] = keccak256("Transfer(address,address,uint256)"))
      const transferEventSignature = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
      if (log.topics[0] !== transferEventSignature) {
        return; // 不是Transfer事件，跳过
      }

      // 验证data字段长度（uint256 = 32字节 = 64个十六进制字符 + 0x前缀）
      if (!log.data || log.data === '0x' || log.data.length < 66) {
        return; // data字段无效，跳过
      }

      // 解析Transfer事件
      const iface = new ethers.Interface([
        'event Transfer(address indexed from, address indexed to, uint256 value)'
      ]);
      
      const parsed = iface.parseLog(log);
      if (!parsed || !parsed.args) return;

      const { from, to, value } = parsed.args;
      
      // 验证解析结果
      if (!from || !to || !value || value === BigInt(0)) {
        return; // 解析结果无效，跳过
      }
      
      // 获取代币信息
      const tokenInfo = await this.getTokenInfo(log.address);
      if (!tokenInfo) return;

      // 计算代币数量
      const tokenAmount = parseFloat(ethers.formatUnits(value, tokenInfo.decimals));
      const valueUSD = tokenAmount * tokenInfo.priceUSD;

      // 检查是否为大额转账
      if (valueUSD < this.getMinTransactionValue()) return;

      const transaction: Transaction = {
        id: `eth_token_${log.transactionHash}_${log.index}`,
        hash: log.transactionHash,
        chain: ChainType.ETHEREUM,
        fromAddress: from,
        toAddress: to,
        value: tokenAmount.toString(),
        valueUsd: valueUSD,
        blockNumber: log.blockNumber,
        timestamp: new Date(),
        tokenAddress: log.address,
        tokenSymbol: tokenInfo.symbol,
        tokenDecimals: tokenInfo.decimals,
        confirmed: true
      };

      logger.warn(`💎 ${tokenInfo.symbol}大额转账: ${valueUSD.toLocaleString('en-US', { style: 'currency', currency: 'USD' })} | 区块: ${log.blockNumber}`);

      if (this.onTransactionCallback) {
        this.onTransactionCallback(transaction);
      }
    } catch (error) {
      // 静默处理解析错误，避免日志刷屏
      logger.debug('ETH代币转账日志解析失败，跳过');
    }
  }

  // 处理单个交易
  private async processTransaction(tx: ethers.TransactionResponse, block: ethers.Block): Promise<void> {
    // 添加详细的交易处理日志
    logger.debug(`🔍 检查交易: ${tx.hash}, value: ${tx.value?.toString()}`);
    
    if (!tx.value || tx.value === BigInt(0)) {
      logger.debug(`⏭️ 跳过零值交易: ${tx.hash}`);
      return;
    }

    // 将wei转换为ETH
    const valueETH = parseFloat(ethers.formatEther(tx.value));
    logger.debug(`💰 交易价值: ${valueETH.toFixed(6)} ETH`);
    
    // 获取ETH当前价格
    const ethPriceUSD = await this.getETHPrice();
    
    // 如果无法获取有效价格，跳过监控
    if (ethPriceUSD <= 0) {
      logger.debug(`⏭️ 无法获取ETH有效价格 (${ethPriceUSD})，跳过交易监控: ${tx.hash}`);
      return;
    }
    
    const valueUSD = valueETH * ethPriceUSD;
    logger.debug(`💰 美元价值: $${valueUSD.toLocaleString()} (ETH价格: $${ethPriceUSD})`);

    // 检查是否为大额交易
    const minValue = this.getMinTransactionValue();
    logger.debug(`📊 阈值检查: $${valueUSD.toLocaleString()} >= $${minValue.toLocaleString()} ? ${valueUSD >= minValue}`);
    
    if (valueUSD < minValue) {
      logger.debug(`⏭️ 交易价值低于阈值，跳过: $${valueUSD.toLocaleString()} < $${minValue.toLocaleString()}`);
      return;
    }

    logger.info(`🎯 发现大额交易！准备处理: ${tx.hash} - $${valueUSD.toLocaleString()}`);

    // 获取地址标签（如果启用）
    let fromLabel, toLabel;
    if (this.addressLabelService) {
      [fromLabel, toLabel] = await Promise.all([
        this.addressLabelService.getAddressLabel(tx.from, ChainType.ETHEREUM),
        tx.to ? this.addressLabelService.getAddressLabel(tx.to, ChainType.ETHEREUM) : null
      ]);
    }

    const transaction: Transaction = {
      id: `eth_${tx.hash}`,
      hash: tx.hash,
      chain: ChainType.ETHEREUM,
      fromAddress: tx.from,
      toAddress: tx.to || '',
      value: ethers.formatEther(tx.value),
      valueUsd: valueUSD,
      blockNumber: tx.blockNumber || 0,
      timestamp: new Date(block.timestamp * 1000),
      gasPrice: tx.gasPrice?.toString(),
      gasUsed: undefined, // 将在交易确认后获取
      tokenSymbol: 'ETH',
      confirmed: true, // 已在区块中的交易视为已确认
      // 地址标签
      fromLabel: fromLabel ? fromLabel.label : undefined,
      toLabel: toLabel ? toLabel.label : undefined
    };

    // 记录地址标签信息
    let logMessage = `🔥 ETH大额交易: ${valueUSD.toLocaleString('en-US', { style: 'currency', currency: 'USD' })} (${valueETH.toFixed(4)} ETH)`;
    if (fromLabel) {
      logMessage += `, 发送方: ${fromLabel.label} (${fromLabel.type})`;
    }
    if (toLabel) {
      logMessage += `, 接收方: ${toLabel.label} (${toLabel.type})`;
    }
    logMessage += ` | 区块: ${tx.blockNumber}`;
    
    logger.warn(logMessage); // 使用warn级别确保显示

    // 调用回调函数
    if (this.onTransactionCallback) {
      this.onTransactionCallback(transaction);
    }
  }

  // 获取ETH价格（使用真实API）
  private async getETHPrice(): Promise<number> {
    return await this.priceService.getETHPrice();
  }

  // 获取ERC-20代币转账
  public async monitorTokenTransfers(): Promise<void> {
    if (!this.wsProvider) return;

    // ERC-20 Transfer事件签名
    const transferTopic = ethers.id('Transfer(address,address,uint256)');

    this.wsProvider.on({
      topics: [transferTopic]
    }, async (log: ethers.Log) => {
      if (!this.isRunning) return;

      try {
        await this.processTokenTransfer(log);
      } catch (error) {
        logger.error('处理代币转账失败:', error);
      }
    });
  }

  // 处理代币转账
  private async processTokenTransfer(log: ethers.Log): Promise<void> {
    try {
      // 检查日志数据是否有效
      if (!log.data || log.data === '0x' || log.data.length < 66) {
        logger.debug(`⏭️ 跳过无效的代币转账日志: ${log.transactionHash}`);
        return;
      }

      // 解析Transfer事件
      const iface = new ethers.Interface([
        'event Transfer(address indexed from, address indexed to, uint256 value)'
      ]);
      
      const parsed = iface.parseLog(log);
      if (!parsed) return;

      const { from, to, value } = parsed.args;
      
      // 获取代币信息
      const tokenInfo = await this.getTokenInfo(log.address);
      if (!tokenInfo) return;

      // 计算代币数量
      const tokenAmount = parseFloat(ethers.formatUnits(value, tokenInfo.decimals));
      const valueUSD = tokenAmount * tokenInfo.priceUSD;

            // 检查是否为大额转账  
      if (valueUSD < this.getMinTransactionValue()) return;

      const transaction: Transaction = {
        id: `eth_token_${log.transactionHash}_${log.index}`,
        hash: log.transactionHash,
        chain: ChainType.ETHEREUM,
        fromAddress: from,
        toAddress: to,
        value: tokenAmount.toString(),
        valueUsd: valueUSD,
        blockNumber: log.blockNumber,
        timestamp: new Date(),
        tokenAddress: log.address,
        tokenSymbol: tokenInfo.symbol,
        tokenDecimals: tokenInfo.decimals,
        confirmed: true
      };

      logger.info(`检测到代币大额转账: ${tokenInfo.symbol}, 金额: $${valueUSD.toLocaleString()}`);

      if (this.onTransactionCallback) {
        this.onTransactionCallback(transaction);
      }
    } catch (error) {
      logger.error('处理代币转账日志失败:', error);
    }
  }

  // 获取代币信息
  private async getTokenInfo(tokenAddress: string): Promise<{symbol: string, decimals: number, priceUSD: number} | null> {
    try {
      const contract = new ethers.Contract(tokenAddress, [
        'function symbol() view returns (string)',
        'function decimals() view returns (uint8)'
      ], this.provider);

      const symbolCall = contract.getFunction('symbol');
      
      // 先只获取symbol，检查白名单后再获取其他信息
      const symbol = await this.queueRequest(() => symbolCall() as Promise<string>);
      if (!symbol) return null;

      // Ethereum链特定验证：阻止原生代币符号
      const invalidSymbols = ['BTC', 'ETH', 'BNB', 'SOL']; // 这些应该是其他链的原生代币
      if (invalidSymbols.includes(symbol.toUpperCase())) {
        // 静默跳过可疑代币，避免日志刷屏
        logger.debug(`跳过可疑代币合约 ${tokenAddress}，声称为 ${symbol}`);
        return null;
      }

      // 立即检查代币是否在监控列表中
      if (!(await this.priceService.isTokenMonitored(symbol))) {
        // 静默跳过，不记录日志避免刷屏
        return null;
      }

      // 只有监控列表中的代币才继续获取详细信息
      const decimalsCall = contract.getFunction('decimals');
      const decimals = await this.queueRequest(() => decimalsCall() as Promise<number>);
      if (!decimals) return null;

      // 获取代币价格
      const priceUSD = await this.getTokenPrice(symbol);
      
      // 如果价格为0，跳过
      if (priceUSD === 0) {
        return null;
      }

      logger.debug(`✅ 检测到白名单代币: ${symbol}, 价格: $${priceUSD}`);
      return { symbol, decimals, priceUSD };
    } catch (error) {
      // 静默处理错误，避免日志刷屏
      return null;
    }
  }

  // 获取代币价格（使用真实API）
  private async getTokenPrice(symbol: string): Promise<number> {
    return await this.priceService.getTokenPrice(symbol);
  }
} 